package websocker;

/**
 * Created by IPE on 2016/12/27.
 */

import net.sf.json.JSONObject;
import org.antlr.tool.Message;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.*;

public class WebsocketEndPoint extends TextWebSocketHandler {
    HashSet<WebSocketSession> set = new HashSet<>();

    Map<String, Integer> hsPop = new HashMap<>();

    JSONObject lastTop=null;

    @Override
    protected void handleTextMessage(WebSocketSession session,
                                     TextMessage message) throws Exception {
        super.handleTextMessage(session, message);

        //记录每个连接
        set.add(session);

        //收取信息
        String text = message.getPayload();
        String username = session.getAttributes().get("username").toString();

        //信息处理
        JSONObject jsonObject = JSONObject.fromObject(text);
        jsonObject.put("sendUser", username);
        if (jsonObject.getString("type") .equals( "pop")) {
            String msg = jsonObject.getString("message");
            if (hsPop.get(msg) == null) hsPop.put(msg, 1);
            else hsPop.put(msg,hsPop.get(msg)+1);

            if(hsPop.size()>13)hsPop.clear();

            List list=WebsocketTool.getTopList(hsPop);
            jsonObject.put("topList",list);
            lastTop=jsonObject;
        }

        //发送准备
        TextMessage returnMessage = new TextMessage(jsonObject.toString());


        //遍历连接并去掉已经关闭的
        Iterator<WebSocketSession> iterator = set.iterator();
        ArrayList<WebSocketSession> delList = new ArrayList<>();
        while (iterator.hasNext()) {
            WebSocketSession it = iterator.next();
            if (it.isOpen()) {
                it.sendMessage(returnMessage);
                System.out.println(it.getId() + "发送成功");
            } else {
                delList.add(it);
            }
        }
        for (WebSocketSession one : delList) {
            set.remove(one);
            System.out.println("删除了无效id:" + one.getId());
        }
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        if(lastTop!=null)session.sendMessage(new TextMessage(lastTop.toString()));
      //  handleTextMessage(session,lastMsg);
      //  System.out.println(session.getAttributes().get("username").toString()+"建立链接");

    }


}
